package com.lbx.controller;

import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author 吕兵星
 * @date 2020/10/25 15:13
 */
@Controller
public class FileController {

    @PostMapping("/upload1")
    public String upLoad(@NotNull @RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        String originalFilename = file.getOriginalFilename();
        System.out.println(originalFilename);
        if (originalFilename == null||"".equals(originalFilename)) {
            return "failure";
        }
        String path = request.getSession().getServletContext().getRealPath("/upload");
        System.out.println(path);
        File savePath = new File(path);
        if (!savePath.exists()){
            savePath.mkdir();
        }



        InputStream inputStream = file.getInputStream();
        FileOutputStream fileOutputStream = new FileOutputStream(new File(savePath,originalFilename));

        int len=0;
        byte[] bytes = new byte[1024];
        while ((len=inputStream.read(bytes))!=-1){
            fileOutputStream.write(bytes,0,len);
            fileOutputStream.flush();
        }
        inputStream.close();
        fileOutputStream.close();

        return "success";
    }
    @PostMapping("/upLoad2")
    public String upLoad2(@NotNull @RequestParam("file") CommonsMultipartFile file, HttpServletRequest request){
        String originalFilename = file.getOriginalFilename();
        if (!"".equals(originalFilename)) {
            String fileName=UUID.randomUUID().toString().replace("-","")+"-"+originalFilename;
            System.out.println(fileName);
            System.out.println(originalFilename);
            String realPath = request.getSession().getServletContext().getRealPath("/upload");
            System.out.println(realPath);
            File savePath = new File(realPath);
            if (!savePath.exists()){
                savePath.mkdir();
            }
            try {
                file.transferTo(new File(savePath+"/"+fileName));
                return "success";
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "failure";
    }
}
